package logger

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
)

type Settings struct {
	*sync.RWMutex
	isMuteMode, isSingleLogFile, isDebug bool
	logPath                              string
}

type SettingsAction func(set *Settings) error

func Setup(actions ...SettingsAction) error {

	if globalSet.RWMutex == nil {
		globalSet.RWMutex = &sync.RWMutex{}
	}

	globalSet.Lock()
	defer globalSet.Unlock()

	tempSet := globalSet

	for _, action := range actions {
		if err := action(&globalSet); err != nil {
			// Recover settings..
			globalSet = tempSet
			return err
		}
	}

	fmt.Printf(`+++Core Logger+++
	path: %s
	debugEnable: %v
	++++++++++++
	`, globalSet.logPath, globalSet.isDebug)

	return nil
}

func SetDebugMode(isDebugMode bool) SettingsAction {
	return func(set *Settings) error {
		set.isDebug = isDebugMode
		return nil
	}
}

// 仅必要输出 var/err
func SetMuteMode(isEnabledMute bool) SettingsAction {
	return func(set *Settings) error {
		set.isMuteMode = isEnabledMute
		return nil
	}
}

func SetOutput(path string, isOneFile bool) SettingsAction {
	return func(set *Settings) error {
		var targetDir string
		set.logPath = path

		if !isOneFile {
			targetDir = path
			set.isSingleLogFile = false
		} else {
			targetDir = filepath.Dir(path)
			set.isSingleLogFile = true
		}

		if err := os.MkdirAll(targetDir, os.ModeDir); err != nil {
			// 除了存在以外都是异常
			if !os.IsExist(err) {
				ShowGuiMsg("盒子日志目录初始化异常", err.Error())
				return err
			}
		}

		return nil
	}

}
